<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑合同' : '新增合同'"
    width="800px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="100px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择合同类型" style="width: 100%">
              <el-option label="服务合同" value="service" />
              <el-option label="采购合同" value="purchase" />
              <el-option label="销售合同" value="sales" />
              <el-option label="租赁合同" value="lease" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="合同标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入合同标题" />
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择合同状态" style="width: 100%">
              <el-option label="草稿" value="draft" />
              <el-option label="审核中" value="reviewing" />
              <el-option label="已批准" value="approved" />
              <el-option label="已签署" value="signed" />
              <el-option label="已过期" value="expired" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="clientId">
            <el-select
              v-model="form.clientId"
              placeholder="请选择客户"
              filterable
              remote
              :remote-method="searchClients"
              style="width: 100%"
            >
              <el-option
                v-for="client in clientOptions"
                :key="client.id"
                :label="client.name"
                :value="client.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同金额" prop="amount">
            <el-input-number
              v-model="form.amount"
              :min="0"
              :precision="2"
              placeholder="请输入合同金额"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签署日期" prop="signDate">
            <el-date-picker
              v-model="form.signDate"
              type="date"
              placeholder="请选择签署日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开始日期" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="date"
              placeholder="请选择开始日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束日期" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="date"
              placeholder="请选择结束日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createContract, updateContract } from '@/api/contract'
import { getClientList } from '@/api/client'
import type { Contract, Client } from '@/types'

interface Props {
  visible: boolean
  formData: Partial<Contract>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const clientOptions = ref<Client[]>([])

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const isEdit = computed(() => !!props.formData.id)

const form = reactive<Partial<Contract>>({
  contractNumber: '',
  title: '',
  type: '',
  status: 'draft',
  clientId: '',
  amount: undefined,
  signDate: '',
  startDate: '',
  endDate: ''
})

const formRules: FormRules = {
  contractNumber: [
    { required: true, message: '请输入合同编号', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入合同标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择合同类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择合同状态', trigger: 'change' }
  ],
  clientId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入合同金额', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ]
}

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    Object.assign(form, {
      contractNumber: '',
      title: '',
      type: '',
      status: 'draft',
      clientId: '',
      amount: undefined,
      signDate: '',
      startDate: '',
      endDate: '',
      ...newData
    })
  },
  { immediate: true, deep: true }
)

// 搜索客户
const searchClients = async (query: string) => {
  try {
    const data = await getClientList({ keyword: query, size: 20 })
    clientOptions.value = data.list
  } catch (error) {
    console.error('搜索客户失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (isEdit.value) {
      await updateContract(form.id!, form)
      ElMessage.success('更新成功')
    } else {
      await createContract(form)
      ElMessage.success('创建成功')
    }
    
    emit('success')
    handleClose()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

onMounted(() => {
  searchClients('')
})
</script>
